package com.gitee.zycra.union.api.common.util;

import org.slf4j.MDC;

import java.net.InetAddress;
import java.security.SecureRandom;
import java.util.Random;

/**
 * @author zycra
 */
public final class TraceIdUtil {

    public static final String TRACE_ID = "traceId";
    private static final String DEFAULT_IP = "00000000";
    private static final Random RANDOM = new SecureRandom();
    private static final int LEFT = 0x000000FF;
    private static final int RIGHT = 0xFFFFFF00;
    private static final int SUB_LENGTH = 6;
    private static final String LOCAL_IP;

    static {
        InetAddress local = IPUtil.getLocalHostAddress();
        if (local == null) {
            LOCAL_IP = DEFAULT_IP;
        } else {
            StringBuilder sb = new StringBuilder();
            byte[] bytes = local.getAddress();
            for (byte b : bytes) {
                sb.append(Integer.toHexString((b & LEFT) | RIGHT).substring(SUB_LENGTH));
            }
            LOCAL_IP = sb.toString().toUpperCase();
        }
    }

    private TraceIdUtil() {
    }

    /**
     * 从MDC取traceId如果没有则生成一个新的
     *
     * @return traceId
     */
    public static String getTraceId() {
        String traceId = MDC.get(TRACE_ID);
        if (traceId != null) {
            return traceId;
        }
        return LOCAL_IP + System.currentTimeMillis() + (Integer.toHexString(RANDOM.nextInt()) + DEFAULT_IP).substring(0, SUB_LENGTH).toUpperCase();
    }

}
